package com.cslg.ac.demo.service.sign;


import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.dao.jedis.JedisDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class SignService {

    @Autowired
    JedisDAO jedisDAO;


    /**
     * 返回今天是否签到
     * @param id
     * @return
     */
    public int SignToday(int id){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        long time = Long.parseLong(sdf.format(date));
        boolean sign = jedisDAO.getbit("user_" + id,time);
        if(sign){
            return ResponseCode.ALREADY_HAVE_SIGN;
        }else {
            return ResponseCode.USER_NOT_SIGN;
        }

    }

    /**
     * 获得连续签到天数
     * @param id
     */
    public Integer getSignDay(int id){
        String key = "user_" + id;
        if(jedisDAO.get(key +"_last") == null){
            return null;
        }
        Integer day;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        long total = jedisDAO.bitcout(key);
        Date dateBefore = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateBefore);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        dateBefore = calendar.getTime();
        long datebefore = Long.parseLong(sdf.format(dateBefore));
        int signToday = SignToday(id);
        boolean flag = jedisDAO.getbit(key,datebefore);
        boolean judge = flag || (total == 1 && signToday == 13);
        if(judge){
            day = Integer.parseInt(jedisDAO.get(key +"_last"));
        }else {
           day = 0;
           jedisDAO.set(key + "_last","0");
        }
        return day;
    }

    /**
     * 貌似可以了，明天再测试一下
     * @param id
     * @return
     */
    public int sign(int id){
        String key = "user_"+id;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        Date dateBefore = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateBefore);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        dateBefore = calendar.getTime();
        long datebefore = Long.parseLong(sdf.format(dateBefore));
        boolean today = jedisDAO.getbit(key,Long.parseLong(sdf.format(date)));
        if(today){
            return ResponseCode.ALREADY_HAVE_SIGN;
        }
        boolean flag = jedisDAO.getbit(key,datebefore);
        jedisDAO.setbit(key,Long.parseLong(sdf.format(date)),"1");
        if(flag){
            jedisDAO.incr(key+"_last");
        }else {
            jedisDAO.set(key+"_last","1");
        }
        return ResponseCode.REQUEST_SUCCESSED;
    }

}
